<?php

/**
 * Created by bingo on 2017/2/6 525945448@qq.com.
 */
namespace app\traits;
use think\Db;
use think\Config;
use think\exception\HttpException;
use think\Loader;
trait Curd
{
    public $select = array(
        'page' => 1,
        'field' => '',
        'orderby' =>'',
        'where' => array(),
        'default_add' => array(),//默认添加的字段
    );
    public function add(){
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $data = array_merge($this->request->except(['id']),$this->select['default_add']);
            // 验证
            try{
                $validate =Loader::validate($controller);;
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }catch (\Exception $e){
                //不捕获异常
            }
            Db::startTrans();
            try {
                $model = Db::name($this->parseTable($controller));
                $ret = $model->insert($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }
            return ajax_return_adv('添加成功');
        } else {
            // 添加
            return view( 'edit');
        }
    }

    public function delete(){
        $controller = $this->request->controller();
        $model = Db::name($this->parseTable($controller));
        try{
            $model->where($this->request->param())->delete();
            return ajax_return_adv("删除成功");
        }catch(\Exception $e){
            return ajax_return_adv_error($e->getMessage());
        }
    }

    public function edit(){
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }
            // 验证
            try{
                $validate =Loader::validate($controller);
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }catch (\Exception $e){
                //不捕获异常
            }
            // 简单的直接使用db更新
            Db::startTrans();
            $model = Db::name($this->parseTable($controller));
            try {
                $model->where('id', $data['id'])->update($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }
            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $model = Db::name($this->parseTable($controller));
            $val = $model->find($id);
            if (!$val) {
                throw new HttpException(404, '该记录不存在');
            }
            return view( $this->request->action() , [ 'val' => $val ]);
        }
    }

    public function index(){
        $model = Db::name($this->parseTable($this->request->controller()));
        //过滤字段
        $table_info = $model->getTableInfo();
        $param = array_merge($this->request->param() , $this->select['where']);
        $map = [];
        foreach ($param as $key => $val) {
            if ($val !== "" && in_array($key, $table_info['fields'])) {
                $map[$key] = $val;
            }
        }
        $field = $this->select['field'] ? $this->select['field'] : '*';
        $orderby = $this->select['orderby'] ? $this->select['orderby'] : ($model->getPk().' desc');
        if ($this->select['page']) {
            // 分页查询
            // 每页数据数量
            $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");
            $list = $model
                ->field($field)
                ->where($map)
                ->order($orderby)
                ->paginate($listRows, false, ['query' => $this->request->get()]);
            $response = ['list' => $list ,"count"=> $list->total() ,"page" => $list->render() ];

        } else {
            // 不开启分页查询
            $list = $model
                ->field($field)
                ->where($map)
                ->order($orderby)
                ->select();
            $response = ['list' => $list ,"count"=> count($list) ,"page" =>'' , 'numPerPage'=> 0 ];
        }
        return view( $this->request->action() , $response);
    }

    public function delete_logic(){

    }

    protected function parseTable($name = '')
    {
        if (!$name) {
            $name = $this->request->controller();
        }

        return str_replace(['/', '.'], '_', $name);
    }
}